import hashlib
import time
import requests
import json
import mimetypes


class Aibayes:
    def __init__(self, app_id=None, app_key=None):
        self.app_id = app_id
        self.app_key = app_key

    def Md5(self, res):
        print(res)
        md = hashlib.md5()  # 构造一个md5
        md.update(res.encode(encoding='utf-8'))
        # 加密
        print(md.hexdigest().upper())
        return md.hexdigest().upper()

    def request(self, tures):
        url = "http://www.aibayes.cn/api/analysis"
        response = requests.post(url, params=tures)
        res = response.json()
        return res.get('data', {})

    def normal_api(self, method=None, imgpath=None):
        if method == 'tiAnalysis':
            method = '9tiAnalysis'
        img_url = self.upload_image(imgpath)
        print(img_url)
        if not img_url:
            print("图片上传失败， 请重试")
            return 
        restime=time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        # restime="20190829114035"
        #传入参数
        tures={
            'timestamp': restime,
            'app_id': self.app_id,
            'version': '1.0',
            'method': method,
            'imgpath': img_url,
            'sign': self.Md5(self.Md5(restime)+self.app_key),
        }
        print(tures)
        return self.request(tures)

    def group_api(self, TongueImgpath=None, FaceImgpath=None):
        restime=time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
        # restime="20190829114035"
        #传入参数
        tures={
            'timestamp': restime,
            'app_id': self.app_id,
            'version': '1.0',
            'method': self.method,
            'FaceImgpath': FaceImgpath,
            'TongueImgpath': TongueImgpath,
            'sign': self.Md5(self.Md5(restime)+self.app_key),
        }
        return self.request(tures)

    def upload_image(self, image):
        url = 'http://python.trust-will.com/apis/v1/views/upload/upload_file'
        try:
            # 打开文件并构建请求
            with open(image, 'rb') as f:
                files = {'files': (f.name, f)}  # 键名根据接口要求调整
                # 发送 POST 请求
                response = requests.post(url, files=files)
                response.raise_for_status()  # 检查 HTTP 错误
                # 返回 JSON 或文本
                res = response.json()
                print(res)
                return res.get('url')
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return None
        except IOError as e:
            print(f"文件读取失败: {e}")
            return None
        except Exception as e:
            print(f"发生未知错误: {e}")
            return None
